import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';

class DatabaseHelper {
  static final _databaseName = "TtsDatabase.db";
  static final _databaseVersion = 1;

  static final table = 'tts_items';
  static final columnTimestamp = 'timestamp';
  static final columnText = 'text';

  // 单例模式确保只有一个数据库实例
  static final DatabaseHelper instance = DatabaseHelper._init();
  static Database? _database;

  DatabaseHelper._init();

  Future<Database> get database async {
    if (_database != null) return _database!;
    _database = await _initDB('$_databaseName');
    return _database!;
  }

  // 初始化数据库
  Future<Database> _initDB(String filePath) async {
    final dbPath = await getDatabasesPath();
    final path = join(dbPath, filePath);

    return await openDatabase(path, version: _databaseVersion, onCreate: _onCreate);
  }

  // 创建表
  Future _onCreate(Database db, int version) async {
    final sql = '''
      CREATE TABLE $table (
        $columnTimestamp INTEGER PRIMARY KEY,
        $columnText TEXT NOT NULL
      )
    ''';
    await db.execute(sql);
  }
}